from twisted.web.resource import Resource
from twisted.web.server import NOT_DONE_YET
from twisted.web import static
from twisted.internet import reactor

from global_r import G
from response import HtmlResponse
from response import TextResponse

class BlockingResource(Resource, object):
    def __init__(self, filename=None, *a):
        self.filename = filename

    def doCall(self, method, reactor, request):
        response = method(request)
        content = response.render(request)
        reactor.callFromThread(request.write, str(content))
        reactor.callFromThread(request.finish)

    def doRender(self, request, renderMethod):
        reactor.callInThread(self.doCall, renderMethod, reactor, request)
        return NOT_DONE_YET

    def render_GET(self, request):
        return self.doRender(request, self._render_GET)

    def render_POST(self, request):
        return self.doRender(request, self._render_POST)

class NoneResource(BlockingResource):
    def _render_GET(self, request):
        return TextResponse('')

class NormalHtmlResource(BlockingResource):
    isLeaf = True

    def __init__(self, filename, *a):
        if filename.startswith('/'):
            filename = filename[1:]
        self.filename = filename

    def _render_GET(self, request):
        self.html = open(self.filename).read()
        return HtmlResponse(self.html)

class FileResource(BlockingResource):
    isLeaf = True

    def __init__(self, filename, *a):
        if filename.startswith('/'):
            filename = filename[1:]
        self.filename = filename

    def _render_GET(self, request):
        return static.File(self.filename)

class AbcResource(BlockingResource):
    rtn = ''
    def _render_GET(self, request):
        print 'Here'
        import time
        time.sleep(3)
        return TextResponse(G.test_var_01)

    def _render_POST(self, request):
        if request.args.get('c'):
            G.test_var_01 = ''
        else:
            G.test_var_01 += '<br/>' + request.args['v'][0]
        return TextResponse(G.test_var_01)
